package cn.fancy.sdk.login.view;

import android.app.Activity;
import android.content.Context;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.fancy.sdk.baseview.BaseView;
import cn.fancy.sdk.baseview.IActivityManager;
import cn.fancy.sdk.common.utils.LoginSwitchManage;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.config.GlobalConfig;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.LoginViewActivity;
import cn.fancy.sdk.login.QdLoginCallback;
import cn.fancy.sdk.login.QdLoginResult;
import cn.fancy.sdk.login.utils.HttpReq;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.SpMmkvUtils;
import cn.fancy.sdk.utils.TipMessSingle;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

//登录或注册后，弹出的实名认证
public class RealViewMust extends BaseView {
    
    private Context mContext = null;
    private EditText etUsername, etCardNum;
    private ImageView mCancleBtn;
    private SdkAsyncTask<String> RealSyncTask = null;
    private SdkAsyncTask<String> loginSyncTask = null;
    private QdLoginCallback callback = null;
    private TextView OkBtn;
    IActivityManager activityMgr;
    private Activity ownerActivity;
    private boolean isBindPhoneHide;
    
    // isBindhide判断是否强制，true点击X进游戏，false点击X返回登陆
    public RealViewMust(Activity cActivity, IActivityManager activityMgr, boolean isBindhide) {
        super(cActivity.getBaseContext(), ResUtil.getLayoutId(
            cActivity.getBaseContext(), "guild_real_view_must"));
        mContext = cActivity.getBaseContext();
        this.activityMgr = activityMgr;
        ownerActivity = cActivity;
        isBindPhoneHide = isBindhide;
        initView();
        CommMessage.sBindAndReal = true;
    }
    
    public RealViewMust(Activity cActivity, IActivityManager activityMgr,
        QdLoginResult qdLoginCallback) {
        super(cActivity.getBaseContext(), ResUtil.getLayoutId(cActivity.getBaseContext(), "guild_real_view_must"));
        mContext = cActivity.getBaseContext();
        this.activityMgr = activityMgr;
        ownerActivity = cActivity;
        if (GlobalConfig.sRegCard == 1) {
            isBindPhoneHide = true;
        } else if (GlobalConfig.sRegCard == 2) {
            isBindPhoneHide = false;
        }
        initView();
        CommMessage.sBindAndReal = true;
    }
    
    
    public RealViewMust(Activity cActivity, IActivityManager activityMgr) {
        super(cActivity.getBaseContext(), ResUtil.getLayoutId(cActivity.getBaseContext(), "guild_real_view_must"));
        mContext = cActivity.getBaseContext();
        this.activityMgr = activityMgr;
        ownerActivity = cActivity;
        if (GlobalConfig.sRegCard == 1) {
            isBindPhoneHide = true;
        } else if (GlobalConfig.sRegCard == 2) {
            isBindPhoneHide = false;
        }
        initView();
        CommMessage.sBindAndReal = true;
    }
    
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.postInvalidate();
        CommMessage.sifReturnLoginView = true;
    }
    
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        CommMessage.sifReturnLoginView = false;
    }
    
    private void initView() {
        etUsername = (EditText) this.findViewById(ResUtil.getId(mContext,
            "et_true_name"));
        etUsername.setInputType(InputType.TYPE_CLASS_TEXT);
        etCardNum = (EditText) this.findViewById(ResUtil.getId(mContext,
            "et_verify_number"));
        OkBtn = (TextView) this.findViewById(ResUtil.getId(mContext,
            "cc_real_confirm"));
        OkBtn.setOnClickListener(this);
        mCancleBtn = (ImageView) this.findViewById(ResUtil.getId(mContext,
            "cancle_new_real_cc"));
        mCancleBtn.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v) {
        if (v.getId() == ResUtil.getId(mContext, "cc_real_confirm")) {
            startRealRequest();
        } else if (v.getId() == ResUtil.getId(mContext, "cancle_new_real_cc")) {
            // yes实名判断不需则进游戏，no是返回登陆
            if (isBindPhoneHide) {
                // 取消实名认证，进行登陆
                if (LoginSwitchManage.getInstance().result_must_ccreal) {
                    Toast.makeText(mContext, TipMessSingle.nine_cancle,
                        Toast.LENGTH_LONG).show();
                }
                Map<String, String> MessReal = GuildBaseInfo.getInstance()
                    .GetLoginAuMess();
                if (MessReal == null) {
                    Toast.makeText(mContext, "信息为空", Toast.LENGTH_LONG).show();
                    GuildBaseInfo.getInstance().clearLogMap();
                    ownerActivity.finish();
                    return;
                }
                String username = MessReal.get("plat_user_name");
                String password = MessReal.get("password");
                GuildBaseInfo.getInstance().clearLogMap();
                startLoginNoReal(username, password);
                Log.e("realuser", "realuser" + username);
            } else {
                Log.e("clickcancle_new_real_cc", "clickcancle_new_real_cc");
                CommMessage.canAutoLogin = false;
                activityMgr.NewpopViewFromStack();
                activityMgr.pushViewToStack(new LoginView(ownerActivity,
                    activityMgr));
             //   Toast.makeText(mContext, TipMessSingle.nine_cancle,
               //     Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    public void commitPeopleMessae(String username, String password,
        String peoplename, String peoplesign) {
    
        final Map<String, String> regMap = GuildBaseInfo.getInstance()
            .realParamReq(mContext, username, password, peoplename,
                peoplesign, "set_idcard");
        RealSyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(regMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                activityMgr.cancelWaitingDialog();
                Log.e("realmustcommitrst", "realmustcommitrst:" + rst);
                if (rst == null) {
                    rst = "";
                }
                if (rst.equals("")) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                        Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    
                    int code = jsonState.getInt("code");
                    Toast.makeText(mContext, jsonState.getString("msg"),
                        Toast.LENGTH_LONG).show();
                    if (code != 1) {
                        return;
                    }
                    // 实名验证成功
                    String dataStr = json.getString("data");
                    JSONObject dataJson = new JSONObject(dataStr);
                    String cmCert = String.valueOf(dataJson.optInt("is_idcard_valid"));
                    
                    CommMessage.setCmCert(cmCert);
                    doWhenPassRequest();
                } catch (JSONException e) {
                    Log.d("BindPhone", "registed phone returns error msg");
                    e.printStackTrace();
                }
                
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
        };
        RealSyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
    public void startRealRequest() {
        String RealUsername = etUsername.getText().toString().trim();
        String RealPeopleSign = etCardNum.getText().toString().trim();
        String username = GuildBaseInfo.getInstance().GetLoginAuMess().get("plat_user_name");
        String password = "";
        String resource = CommMessage.getRealType();
        String user_id = GuildBaseInfo.getInstance().GetLoginAuMess().get("user_id");
        
        if (callback != null) {
            resource = "gameReal";
        }
        
        if (resource.equals("login") || resource.equals("register")) {
            Map<String, String> MessReal = GuildBaseInfo.getInstance()
                .GetLoginAuMess();
            if (MessReal != null) {
                username = MessReal.get("plat_user_name");
                password = MessReal.get("password");
                Log.e("realusernameMessReal", "realusernameMessReal" + username);
            }
        } else if (resource.equals("gameReal")) {
            username = GuildBaseInfo.getInstance().getYuanpfusername();
            password = GuildBaseInfo.getInstance().getYuanpassword();
            Log.e("realusernamegameReal", "realusernamegameReal" + username);
        }
        
        if (!NetworkImpl.isNetworkConnected(mContext)) {
            Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        
        commitPeopleMessae(username, password, RealUsername, RealPeopleSign);
    }
    
    private void doWhenPassRequest() {
        Log.d("realviewmust_dowhenpass", "realviewmust_dowhenpass");
        if (callback != null) {
            String antisign = CommMessage.getCmCert();
            callback.callback(QdLoginCallback.GET_ANTI_SIGN_SUCCESS, antisign,
                null);
            // ownerActivity.finish();
            activityMgr.NewpopViewFromStack();
            return;
        }
        Map<String, String> MessReal = GuildBaseInfo.getInstance()
            .GetLoginAuMess();
        if (MessReal != null) {
            String username = MessReal.get("plat_user_name");
            String password = MessReal.get("password");
            GuildBaseInfo.getInstance().clearLogMap();
            startLogin(username, password);
        }
    }
    
    private void startLogin(final String platformuid, String pass) {
        final Map<String, String> params = GuildBaseInfo.getInstance()
            .buildLoginGuild(mContext, platformuid, pass);
        if (params == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_LONG).show();
            return;
        }
        
        // 进行登录请求
        loginSyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(params);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                Log.e("realviewstartrst", "realviewstartrst" + rst);
                activityMgr.cancelWaitingDialog();
                if (rst == null) {
                    rst = "";
                }
                if ("".equals(rst)) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                        Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    
                    int code = jsonState.getInt("code");
                    Toast.makeText(mContext, jsonState.getString("msg"), Toast.LENGTH_LONG).show();
                    if (code != 1) {
                        return;
                    }
                    String msg = json.getString("data");
                    JSONObject msgjson = new JSONObject(msg);
    
                    String user_id = "";
                    String token = GlobalConfig.ticket;
                    String time = GlobalConfig.stime;
                    if (msgjson.has("id")) {
                        user_id = msgjson.optString("id");
                        token = msgjson.optString("ticket");
                        time = String.valueOf(msgjson.getInt("expires_in"));
                    } else if (msgjson.has("user_id")) {
                        user_id = msgjson.optString("user_id");
                    }
    
                    String need_bind_flag = "";
                    if (msg.equals("")) {
                        return;
                    }
    
                    if (TextUtils.isEmpty(msgjson.optString("float_window_url"))) {
                        String httpsFloatUrl = msgjson.getString("float_window_url");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_HTTPS_FLOAT_URL, httpsFloatUrl);
                    }
    
                    if (!TextUtils.isEmpty(msgjson.optString("game_discount"))) {
                        String discount = msgjson.getString("game_discount");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, discount);
                    }else {
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, "0");
                    }
                    
                    QdLoginResult loginResult = new QdLoginResult(
                        user_id, platformuid, token, time, "0",
                        need_bind_flag);
                    
                    activityMgr.notifyLoginSuccess(loginResult);
                    activityMgr.finishDialogOrActivity();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            
            }
            
        };
        
        loginSyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
    private void startLoginNoReal(String platformuid, String pass) {
        final String uname = platformuid;
    
        final Map<String, String> params = GuildBaseInfo.getInstance()
            .loginNoReal(mContext, uname, pass, "login");
        Log.e("realmustparams", "realmustparams" + params);
        
        if (params == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_LONG).show();
            return;
        }
        
        // 进行登录请求
        loginSyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(params);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                activityMgr.cancelWaitingDialog();
                if (TextUtils.isEmpty(rst)) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    Log.e("realviewmustrst", "realviewmustrst" + rst);
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG).show();
                        return;
                    }
                    
                    String msg = json.getString("data");
                    String need_bind_flag = "";
                    if (msg != null && !msg.equals("")) {
                        JSONObject msgjson = new JSONObject(msg);
                        String user_id = msgjson.optString("id");
                        String token = msgjson.optString("ticket");
                        String time = "0";
                        
                        QdLoginResult loginResult = new QdLoginResult(
                            user_id, uname, token, time, "0",
                            need_bind_flag);
                        if (activityMgr instanceof LoginViewActivity) {
                            ((LoginViewActivity) activityMgr)
                                .staticnotifyLoginSuccess(
                                    loginResult, mContext);
                        }
                        activityMgr.finishDialogOrActivity();
                    }
                    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            
            }
            
        };
        loginSyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
}
